package portlet.backing;

import java.io.File;
import java.io.IOException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import javax.faces.context.FacesContext;

import javax.faces.event.ActionEvent;

import javax.faces.event.ValueChangeEvent;

import javax.faces.model.SelectItem;

import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.ReadOnlyException;
import javax.portlet.ValidatorException;
import javax.portlet.WindowState;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.rich.input.RichSelectManyShuttle;
import oracle.adf.view.rich.component.rich.input.RichSelectOneChoice;

import oracle.adf.view.rich.component.rich.input.RichSelectOrderShuttle;

import oracle.jbo.ViewCriteria;
import oracle.jbo.ViewCriteriaItem;
import oracle.jbo.ViewCriteriaRow;
import oracle.jbo.ViewObject;

import oracle.jbo.common.JboCompOper;

import oracle.stellent.ridc.IdcClient;
import oracle.stellent.ridc.IdcContext;
import oracle.stellent.ridc.model.DataBinder;
import oracle.stellent.ridc.model.DataObject;
import oracle.stellent.ridc.model.DataResultSet;

import oracle.stellent.ridc.protocol.ServiceResponse;

import oracle.webcenter.framework.view.JSFUtils;
import oracle.webcenter.navigationframework.NavigationResource;
import oracle.webcenter.portalframework.sitestructure.SiteStructure;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import portlet.RSS;

import portlet.Utils;

import portlet.resource.RSSBundle;

public class RSSBacking {
    private String mPortletTitle;
    private String mActive;
    private RichSelectOneChoice selectChoice;
    private String viewRender1;
    private String viewRender2;
    private int numberOfResult = 0;
    private List<String> lstChuyenmucLuaChon = new ArrayList<String>();
    private RichSelectOrderShuttle selectOrderShuttleChuyenmuc;
    private List<SelectItem> lstChuyenmuc = new ArrayList<SelectItem>();
    private List<DataObject> lstResult = new ArrayList<DataObject>();
    private String langid;
    private String urlChitiet;
    private String urlFile;
    private boolean hasFile = false;

    Timer timer;
    private final static long HOURS_24 = 24 * 60 * 60 * 1000; //miliseconds

    public RSSBacking() {
        getLangid();
        getUrlChitiet();
    }

    public String getViewRender1() {
        loadFile();
        return viewRender1;
    }

    public String getViewRender2() {
        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            ViewObject vo = getRssViewObject();
            if (vo.getAllRowsInRange().length > 0) {
                Object active = vo.getCurrentRow().getAttribute("Active");
                if (active != null) {
                    selectChoice.setValue(Integer.valueOf(active.toString()));
                    //AdfFacesContext.getCurrentInstance().addPartialTarget(selectChoice);
                }
                Object lstCm = vo.getCurrentRow().getAttribute("MuctinId");
                if (lstCm != null) {
                    String arrChuyenmuc[] = lstCm.toString().split(",");
                    selectOrderShuttleChuyenmuc.setValue(null);
                    lstChuyenmucLuaChon.clear();
                    for (int i = 0; i < arrChuyenmuc.length; i++) {
                        lstChuyenmucLuaChon.add(arrChuyenmuc[i]);
                    }
                    selectOrderShuttleChuyenmuc.setValue(lstChuyenmucLuaChon);
                }
            }
        }
        return viewRender2;
    }

    private ViewObject getRssViewObject() {
        DCIteratorBinding rssIterator =
            Utils.getIteratorBinding("RssCauhinhView1Iterator");
        ViewObject vo = rssIterator.getViewObject();
        ViewCriteria vc = vo.createViewCriteria();
        vc.setName("RSSCriteria");
        ViewCriteriaRow vcRow = vc.createViewCriteriaRow();
        ViewCriteriaItem rowViewCriteriaItem =
            vcRow.ensureCriteriaItem("NgonNgu");
        rowViewCriteriaItem.setOperator(JboCompOper.OPER_EQ);
        rowViewCriteriaItem.setValue(langid);
        vc.addRow(vcRow);
        vo.getViewCriteriaManager().removeApplyViewCriteriaName("RSSCriteria");
        vo.applyViewCriteria(vc);
        vo.executeQuery();
        if (vo.getAllRowsInRange().length > 0) {
            vo.setCurrentRowAtRangeIndex(0);
        }
        return vo;
    }

    private void loadFile() {
        ViewObject vo = getRssViewObject();
        if (vo.getAllRowsInRange().length > 0) {
            Object FileId = vo.getCurrentRow().getAttribute("FileId");
            DCIteratorBinding fileIterator =
                Utils.getIteratorBinding("HtFileView1Iterator");
            ViewObject vo1 = fileIterator.getViewObject();
            ViewCriteria vc1 = vo1.createViewCriteria();
            ViewCriteriaRow cr1 = vc1.createViewCriteriaRow();
            String varStr = "IN (0)";
            if (FileId != null) {
                hasFile = true;
                varStr = "IN (" + FileId.toString() + ")";
            }
            cr1.setAttribute("Id", varStr);
            vc1.addElement(cr1);
            vo1.getViewCriteriaManager().clearViewCriterias();
            vo1.applyViewCriteria(vc1);
            vo1.executeQuery();
        }
    }

    public void RSSUpdateTask() {
        DCIteratorBinding rssIterator =
            Utils.getIteratorBinding("RssCauhinhView1Iterator");
        if (rssIterator.getAllRowsInRange().length > 0) {
            rssIterator.setCurrentRowWithKeyValue(langid);
            if (mActive == null) {
                mActive =
                        rssIterator.getCurrentRow().getAttribute("Active").toString();
            }
            rssIterator.getCurrentRow().setAttribute("Active", mActive);
            String lstCm = "";
            for (String chuyenmuc : lstChuyenmucLuaChon) {
                lstCm += chuyenmuc + ",";
            }
            lstCm = lstCm.substring(0, lstCm.lastIndexOf(","));
            rssIterator.getCurrentRow().setAttribute("MuctinId", lstCm);
            WriteRSS();
            Utils.execute("Commit");
            if (rssIterator.getAllRowsInRange().length > 0) {
                String active =
                    rssIterator.getCurrentRow().getAttribute("Active").toString();
                if (active.equals("1")) {
                    String rTime =
                        rssIterator.getCurrentRow().getAttribute("Runtime").toString();
                    String arrTime[] = rTime.split(":");
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.HOUR_OF_DAY,
                                 Integer.valueOf(arrTime[0]));
                    calendar.set(Calendar.MINUTE, Integer.valueOf(arrTime[1]));
                    calendar.set(Calendar.SECOND, Integer.valueOf(arrTime[2]));
                    Date time = calendar.getTime();
    
                    timer = new Timer();
                    timer.scheduleAtFixedRate(new RemindTask(), time, HOURS_24);
                } else {
                    timer.cancel();
                }
            }
        }
    }

    public static DataResultSet getViewInfor(String viewName, String tableName,
                                             IdcClient client,
                                             IdcContext userContext) {
        DataResultSet obj = null;
        try {
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "GET_SCHEMA_VIEW_VALUES");
            dataBinder.putLocal("schViewName", viewName.toUpperCase());
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            obj = binder.getResultSet(tableName.toUpperCase());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    class RemindTask extends TimerTask {
        public void run() {
            WriteRSS();
        }
    }

    private void WriteRSS() {
        // Danh sach Feed trong file RSS
        if (lstChuyenmucLuaChon.size() > 0) {
            DCIteratorBinding rssIterator =
                Utils.getIteratorBinding("RssCauhinhView1Iterator");
            if (rssIterator.getAllRowsInRange().length > 0) {
                rssIterator.setCurrentRowWithKeyValue(langid);
                DCIteratorBinding fileIterator =
                    Utils.getIteratorBinding("HtFileView1Iterator");
                Object newFile = null;
                ArrayList<String> newFileList = new ArrayList<String>();
                if (rssIterator.getAllRowsInRange().length > 0) {
                    //Xoa thong tin file rss trong bang HtFile
                    Object oldFile =
                        rssIterator.getCurrentRow().getAttribute("FileId");
                    if (oldFile != null) {
                        String rssFile[] = oldFile.toString().split(",");
                        for (int i = 0; i < rssFile.length; i++) {
                            fileIterator.setCurrentRowWithKeyValue(rssFile[i]);
                            fileIterator.removeCurrentRow();
                        }
                    }
                }

                for (String chuyenmuc : lstChuyenmucLuaChon) {
                    //Lay ten chuyen muc
                    String filename = chuyenmuc;
                    for (int j = 0; j < lstChuyenmuc.size(); j++) {
                        if (chuyenmuc.equals(lstChuyenmuc.get(j).getValue())) {
                            filename = lstChuyenmuc.get(j).getLabel();
                        }
                    }

                    String copyright = "Copyright hold by SSC";
                    String title = filename;
                    String description = "RSS Feeds";
                    String language = langid;
                    String link = "http://www.ssc.gov.vn";
                    Calendar cal = new GregorianCalendar();
                    Date creationDate = cal.getTime();
                    SimpleDateFormat date_format =
                        new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z",
                                             Locale.US);
                    String pubdate = date_format.format(creationDate);
                    
                    String url = urlChitiet + "?dDocName=";
                    Feed rssFeeder =
                        new Feed(title, link, description, language, copyright,
                                 pubdate);
                    FeedMessage feed;
                    List<DataObject> lst = getListNews(chuyenmuc);
                    if (lst.size() > 0) {
                        int size = lst.size();
                        if (lst.size() > 25) {
                            size = 25;
                        }
                        for (int i = 0; i < size; i++) {
                            feed = new FeedMessage();
                            feed.setTitle(lst.get(i).get("dDocTitle"));
                            feed.setDescription(lst.get(i).get("xComments"));
                            feed.setAuthor("tanbd@tinhvan.com");
                            feed.setGuid(url + lst.get(i).get("dDocName"));
                            feed.setLink(url + lst.get(i).get("dDocName"));
                            feed.setPubDate(lst.get(i).get("xmNgayxuatban").toString());
                            rssFeeder.getMessages().add(feed);
                        }
                    }
                    // Ghi ra file
                    String dirRoot =
                        Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"); //Thu muc file goc
                    String dirFile =
                        Utils.ENUM_CAU_HINH_KHOA.RSS_DIR.getValue("HtCauHinhView1Iterator"); //duong dan tuong doi thu muc file
                    File dir = new File(dirRoot, dirFile);

                    File fullPath = new File(dir, filename + ".rss");
                    if (fullPath.getParentFile().exists() == false) {
                        fullPath.getParentFile().mkdirs();
                    }
                    File filePath = new File(dirFile, filename + ".rss");
                    RSSFeedWriter writer =
                        new RSSFeedWriter(rssFeeder, fullPath.toString());
                    try {
                        writer.write();
                        Utils.execute("HtFileInsert");
                        if (fileIterator.getCurrentRow() != null) {
                            newFile =
                                    fileIterator.getCurrentRow().getAttribute("Id");
                            fileIterator.getCurrentRow().setAttribute("TenFile",
                                                                      filename);
                            fileIterator.getCurrentRow().setAttribute("DuongDan",
                                                                      filePath.toString().replace("\\",
                                                                                                  "/"));
                            fileIterator.getCurrentRow().setAttribute("MaUngDung",
                                                                      Utils.ENUM_MA_UNG_DUNG.RSS.getMaUngDung());
                            newFileList.add(newFile.toString());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //Them file rss vao db
                if (newFileList.size() > 0) {
                    String newRssFileId = "";
                    for (int i = 0; i <= newFileList.size() - 1; i++) {
                        newRssFileId += newFileList.get(i) + ",";
                    }
                    newRssFileId =
                            newRssFileId.substring(0, newRssFileId.lastIndexOf(","));
                    rssIterator.getCurrentRow().setAttribute("FileId",
                                                             newRssFileId);
                }
            }
        }
    }

    private List<DataObject> getListNews(String chuyenmuc) {
        int startRow = 0;
        int endRow = 24;
        try {
            numberOfResult = 25;
            String querystring = createQuery(chuyenmuc, langid);
            DataResultSet drs =
                SearchUCMContent(querystring, "xmNgayxuatban", numberOfResult,
                                 startRow, endRow, "DESC",
                                 Global.getIdcClient(),
                                 Global.getUserContext());
            lstResult = drs.getRows();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lstResult;
    }

    private DataResultSet SearchUCMContent(String queryString,
                                           String sortField,
                                           int numberofResult, int startRow,
                                           int endRow, String sortOrder,
                                           IdcClient client,
                                           IdcContext userContext) {
        DataResultSet obj = null;
        try {
            DataBinder dataBinder = client.createBinder();
            dataBinder.putLocal("IdcService", "GET_SEARCH_RESULTS");
            dataBinder.putLocal("QueryText", queryString);
            dataBinder.putLocal("SortField", sortField);
            if (numberofResult > 0)
                dataBinder.putLocal("ResultCount",
                                    String.valueOf(numberofResult));
            if (startRow > 0)
                dataBinder.putLocal("StartRow", String.valueOf(startRow));
            if (endRow > 0)
                dataBinder.putLocal("EndRow", String.valueOf(endRow));
            if (sortOrder != null && sortOrder.length() > 0)
                dataBinder.putLocal("SortOrder", sortOrder);
            ServiceResponse ridc_response;
            ridc_response = client.sendRequest(userContext, dataBinder);
            DataBinder binder = ridc_response.getResponseAsBinder();
            obj = binder.getResultSet("SearchResults");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return obj;
    }

    private String createQuery(String chuyenmuc, String ngonnguid) {
        String queryString =
            "(dDocType <contains> `Tinbai`) <AND> xmHienthi <contains> `True` <AND> xmNgayxuatban <= `<$dateCurrent(0)$>`";
        if (chuyenmuc != null) {
            queryString += " <AND> (";
            queryString +=
                    " xmChuyenmuctin <contains> `" + chuyenmuc + "` <OR> xmMuctinhienthi <contains> `" +
                    chuyenmuc + "` <OR> ";
            queryString =
                    queryString.substring(0, queryString.lastIndexOf("<OR>"));
            queryString += ")";
        }
        return queryString;
    }

    public String getUrlChitiet() {
        try {
            urlChitiet = Utils.getPortletRequest().getParameter("urlChitiet");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlChitiet;
    }

    public String getUrlFile() {
        try {
            urlFile = Utils.getPortletRequest().getParameter("urlFile");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlFile;
    }

    public void setHasFile(boolean hasFile) {
        this.hasFile = hasFile;
    }

    public boolean isHasFile() {
        return hasFile;
    }

    public void activeValueChanged(ValueChangeEvent valueChangeEvent) {
        mActive = valueChangeEvent.getNewValue().toString();
    }

    public void setSelectChoice(RichSelectOneChoice selectChoice) {
        this.selectChoice = selectChoice;
    }

    public RichSelectOneChoice getSelectChoice() {
        return selectChoice;
    }

    public void setNumberOfResult(int numberOfResult) {
        this.numberOfResult = numberOfResult;
    }

    public int getNumberOfResult() {
        return numberOfResult;
    }

    public void setLstChuyenmucLuaChon(List<String> lstChuyenmucLuaChon) {
        this.lstChuyenmucLuaChon = lstChuyenmucLuaChon;
    }

    public List<String> getLstChuyenmucLuaChon() {
        return lstChuyenmucLuaChon;
    }

    public String getLangid() {
        langid = Utils.getPortalLocale().getLanguage();
        return langid;
    }

    public void setLstChuyenmuc(List<SelectItem> lstChuyenmuc) {
        this.lstChuyenmuc = lstChuyenmuc;
    }


    private void loadChuyenmuc() {
        DataResultSet rs =
            this.getViewInfor("CHUYENMUCTIN_VIEW", "CHUYENMUCTIN",
                              Global.getIdcClient(), Global.getUserContext());
        List<DataObject> lstObj = rs.getRows();
        for (DataObject obj : lstObj) {
            if (obj.get("NGONNGU").toString().equals(langid)) {
                SelectItem item = new SelectItem();
                item.setLabel(obj.get("CHUYENMUC"));
                item.setValue(obj.get("ID"));
                lstChuyenmuc.add(item);
            }
        }
    }

    public List<SelectItem> getLstChuyenmuc() {
        loadChuyenmuc();
        return lstChuyenmuc;
    }

    public void setLstResult(List<DataObject> lstResult) {
        this.lstResult = lstResult;
    }

    public List<DataObject> getLstResult() {
        return lstResult;
    }

    public String getPortletTitle() {
        try {
            if (mPortletTitle == null) {
                PortletPreferences preferences =
                    Utils.getPortletRequest().getPreferences();
                mPortletTitle =
                        preferences.getValue(RSS.PORTLETTITLE_KEY, Utils.getResource(RSSBundle.PORTLETTITLE));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getPortletTitleLabel() {
        //String resource = Utils.getResource(RSSBundle.PORTLETTITLE);
        return null;
    }

    public void setPortletTitle(String portletTitle) {
        mPortletTitle = portletTitle;
    }

    public void setMActive(String mActive) {
        this.mActive = mActive;
    }

    public String getMActive() {
        return mActive;
    }

    public void setSelectOrderShuttleChuyenmuc(RichSelectOrderShuttle selectOrderShuttleChuyenmuc) {
        this.selectOrderShuttleChuyenmuc = selectOrderShuttleChuyenmuc;
    }

    public RichSelectOrderShuttle getSelectOrderShuttleChuyenmuc() {
        return selectOrderShuttleChuyenmuc;
    }
}
